package com.g2room.search.es.op;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.g2room.search.es.engine.EsClient;
public class Index {
	private EsClient esClient;
	public Index(){
//		esClient = new EsClient("218.29.188.54", "9301", "myuall", "myuall");
		esClient = new EsClient("47.94.230.215", "9001", "myuall", "myuall");
	}
	public Index(String index){
		esClient = new EsClient(index);
	}
	

	public static void main(String[] args) {
		String index = "myuall";
//		Index idx  = new Index(index);
//		idx.createIndex(1484+"", json, type);
////		idx.createIndex("1", json, type);
//		MajorInfo mi = new MajorInfo();
//		mi.setName("经济学科");
//		mi.setCode("00225");
//		mi.setId(5);
//		idx.createIndex(mi.getId()+"", JSON.toJSONString(mi), type);
		String type = "lifeFood";
		Map<String, String> param = new HashMap<String, String>();
//		param.put("type", "11");
		Index idx = new Index();
		boolean rs = idx.delIndex("25", type);
		System.out.println(rs+"=");
		
//		idx.esClient = new EsClient("218.29.188.54", "9301", "myuall", "myuall");
//		for(int i = 0; i< 150; i++) {
//			boolean rs = idx.delIndex("25", type);
//			System.out.println(rs+"=");
//		}
		
//		Search search = new Search(index);
//		SearchResultPageTo srpt = search.searchAndPage(param, type, 0, 10000);
//		System.out.println("=======" + srpt.getData().size());
//		List<String> ids = new ArrayList<String>();
//		for(Map<String,Object> map : srpt.getData()) {
//			ids.add(map.get("id").toString());
//			System.out.println(map.get("id").toString());
//			boolean rs = idx.delIndex(map.get("id").toString(), type);
//			System.out.println(rs+"=");
//		}
	}
	
	/**
	 * 批量删除索引
	 * @param ids
	 * @param type
	 * @return	删除成功返回true，反之返回false，包括只删除一部分也返回false。
	 */
	public boolean delIndexes(List<String> ids, String type) {
		boolean rs = true;
		int i = 0;
		for(String id : ids) {
			System.out.print("," + i);
			DeleteResponse dr = esClient.getClient().prepareDelete(esClient.getIndex(), type, id).setRouting("id").execute().actionGet(); 
			if(rs) rs = dr.isFound();
			i++;
		}
		return rs;
	}
	
	/**
	 * 单个删除索引
	 * @param id
	 * @param type
	 * @return 删除成功返回true，反之返回false
	 */
	public boolean delIndex(String id, String type) {
		DeleteResponse dResponse = esClient.getClient().prepareDelete(esClient.getIndex(), type, id).setRouting("id").execute()
                .actionGet();
		return dResponse.isFound();
	}
	
	// 清除所有索引
    public boolean deleteIndex() {
        IndicesExistsResponse indicesExistsResponse = esClient.getClient().admin().indices()
                .exists(new IndicesExistsRequest(new String[] {esClient.getIndex()}))
                .actionGet();
        DeleteIndexResponse  dir = null;
        if (indicesExistsResponse.isExists()) {
        	dir = esClient.getClient().admin().indices().delete(new DeleteIndexRequest(esClient.getIndex()))
                    .actionGet();
        }
    	return dir.isContextEmpty();
    }
    
    // 删除Index下的某个Type
    public boolean deleteType(String type) throws UnknownHostException{
    	StringBuilder b = new StringBuilder("");
        b.append("{");
        b.append("  \"range\": {");  
        b.append("      \"id\": {");
        b.append("          \"from\": 0," );
        b.append("          \"to\": 90000" );
        b.append("      }");
        b.append("  }");
        b.append("}");
    	
        TransportClient client = TransportClient.builder().settings(getSettings()).build();

		client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("218.29.188.54"), 9301));
    	
//		DeleteByQueryRequestBuilder dqrb = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE)
//            .setTypes(type)
//            .setSource(b.toString());
//		DeleteByQueryResponse rsp = dqrb.execute().actionGet();
    	
//    	esClient.getClient().prepareDeleteByQuery().
//    	esClient.getClient().prepareDelete().setIndex(esClient.getIndex()).setType(type).setId(id).execute().actionGet();
//    	DeleteResponse dResponse = esClient.getClient().prepareDelete().setIndex(esClient.getIndex()).setType(type).execute().actionGet();
//    	return rsp.isContextEmpty();//.isFound();
    	return false;
    }

	private Settings getSettings() {
		Settings settings = Settings.settingsBuilder()
		// 设置分片
		.put("number_of_shards", 5)
		// 设置集群名称
		.put("cluster.name", "myuall")
		.put("client.transport.sniff", true)
		// 设置副本数量
		.put("number_of_replicas", 1)
		.build();
		return settings;
	}
	
	/**
	 * 插入数据到ES
	 * @param id	插入的文档ID
	 * @param json	json数据
	 * @param index	
	 * @param type
	 * @return	插入则返回true，暂时未验证更新返回值
	 */
	public boolean createIndex(String id, String json, String type) {
		IndexRequestBuilder irb = esClient.getClient().prepareIndex(esClient.getIndex(), type);
		String routing = EsClient.getRouting(type);
		if(null != routing) irb.setRouting(routing);
		irb.setId(id);
		irb.setSource(json);
//		irb.field("analyzer","ik");
		IndexResponse ir = irb.execute().actionGet();
		return ir.isCreated();
	}
	
	/**
	 * 批量插入数据到ES
	 * @param ids	插入的ID集合
	 * @param jsons	json数据集合
	 * @param index
	 * @param type
	 * @return
	 */
	public boolean createIndexBatch(List<String> ids, List<String> jsons, String type) {
		boolean rs = false;
		if(null == jsons || jsons.isEmpty()) return rs;
		
		Client client = esClient.getClient();
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		String routing = EsClient.getRouting(type);
		for(int i =0; i< ids.size(); i++) {
			IndexRequestBuilder irb = client.prepareIndex(esClient.getIndex(), type);
			if(null != routing) irb.setRouting(routing);
			irb.setId(ids.get(i));
			bulkRequest.add(irb.setSource(jsons.get(i)));
		}
		BulkResponse br = bulkRequest.execute().actionGet();
		System.out.println("====="+br.buildFailureMessage());
		rs = br.hasFailures();
		return rs;
	}
}
